package com.dst.smart.handler.disposer;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dst.smart.app.MainActivity;
import com.dst.smart.handler.entity.SemanticResult;
import com.dst.smart.handler.entity.ServiceType;
import com.dst.smart.music.MusicPlayMedia;
import com.dst.smart.player.entity.SongPlayInfo;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

/**
 *	笑话
 * 	讲个笑话
 	我想听笑话
 *
 * author <a href="http://www.xfyun.cn">讯飞开放平台</a>
 * date 2016年9月5日 下午4:58:10
 *
 */
public class JokeDisposer extends Disposer{

	public JokeDisposer(Context context) {
		super(context);
	}

	@Override
	public void disposeResult(SemanticResult semanticResult) {

		try {
			if (semanticResult != null) {
			JSONArray result = semanticResult.getResult();
			if(result == null || result.length() == 0) return;
			if(MainActivity.musicIsSong) {
				JSONObject entry = result.getJSONObject(0);
				if (!TextUtils.isEmpty(entry.optString("content"))) {
					String conent = entry.getString("content");
					String title = entry.optString("title");
					getPlayController().playURLList(semanticResult.getUUID(), null);
					getPlayController().playText(semanticResult.getUUID(),
							"请听笑话，" + title + "。" + conent, true, "", null);
				} else {
					List<SongPlayInfo> playList = new ArrayList<SongPlayInfo>();
					for (int index = 0; index < result.length(); index++) {
						entry = result.getJSONObject(index);
						SongPlayInfo songPlayInfo = new SongPlayInfo();
						songPlayInfo.setPlayUrl(entry.optString("mp3Url"));
						songPlayInfo.setAnswerText("***");
						playList.add(songPlayInfo);
					}
					try {
						if (MusicPlayMedia.getInstansMedia() == null) {
							new MusicPlayMedia(mContext, "");
						}
						MusicPlayMedia.getInstansMedia().playURLList(playList);
						MusicPlayMedia.getInstansMedia().setFileName(1,
								playList.get(0).getPlayUrl(), 1);
						MusicPlayMedia.getInstansMedia().play();
						if (semanticResult.getAnswerText().length() > 0) {
							//先播放標題
							getPlayController().playURLList(semanticResult.getUUID(), null);
							getPlayController().playText(semanticResult.getUUID(), semanticResult.getAnswerText(), true, "", null);
						}
						sendAiuiData("笑话", "joke", result.toString());
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	public boolean canHandle(ServiceType type){
		return (type == ServiceType.JOKE);
	}

}
